local  geo_center  	    = lo_to_geo_coords(0,0)
local  lo_1   = geo_to_lo_coords(geo_center.lat + 0.1,geo_center.lon)
local  lo     = geo_to_lo_coords(geo_center.lat      ,geo_center.lon + 0.1)

local  dist_1         = math.sqrt(lo_1.z * lo_1.z + lo_1.x * lo_1.x) * 10
meters_per_lon_degree = math.sqrt(lo.x * lo.x     + lo.z * lo.z) * 10
lat_lon_aspect 		  = meters_per_lon_degree/dist_1
device_timer_dt			  = 0.05

function NM(nm)
	return nm * 1852.0 / meters_per_lon_degree
end

chart_defaults = 
{
	{scale = NM(5)  ,chart =3 },
	{scale = NM(10) ,chart =3 },
	{scale = NM(20) ,chart =5 },
	{scale = NM(40) ,chart =6 },
	{scale = NM(80) ,chart =7 },
	{scale = NM(160),chart =8 },
}

default_scale = chart_defaults[2].scale
default_chart = chart_defaults[3].chart

function default_map(i)
	return {scale = chart_defaults[i].scale,
			chart = chart_defaults[i].chart,
			dont_use_in_waypoint_check = true}
end

local dbg_map_center = {42 - 0.3,42}
local dbg_map_sz	 = 0.3

function dbg_zone_point(p_lon,p_lat)
	return {dbg_map_center[1] + p_lat * dbg_map_sz, dbg_map_center[2] + p_lon * dbg_map_sz}
end

zones =
{
	[1] =  { dbg_zone_point(-0.5,0.1),dbg_zone_point(0.3,0.8),dbg_zone_point(0.8,-0.9),dbg_zone_point(-0.7,-0.5),dbg_zone_point(0,0),dbg_zone_point(-0.5,0.1)}
}

need_to_be_closed  = true

local aspect_ratio_fov  = 0.214/0.142

function test_contain(map,threshold,latitude,longitude)
	if map.dont_use_in_waypoint_check or 
	   map.latitude  == nil or 
	   map.longitude == nil then
	   return false
	end
	local x_max = map.scale *( 1 - threshold) 
	local y_max = map.scale *( aspect_ratio_fov - threshold) 
	
	local d_lat = (latitude  - map.latitude) / lat_lon_aspect
	local d_lon =  longitude - map.longitude
	
	if 	map.rotation ~= nil then
		local sin_a = math.sin(-map.rotation)
		local cos_a = math.cos(-map.rotation)
		local x = d_lon
		local y = d_lat
		
		d_lon = x * cos_a - y * sin_a	  
		d_lat = x * sin_a + y * cos_a
	end

	return math.abs(d_lon) < x_max and
		   math.abs(d_lat) < y_max		   
end

function on_waypoint_adding(lat,lon,course)

	if not map_pages then
		map_pages = {}
	else
		for i,map in ipairs(map_pages) do
			if test_contain(map,0.01,lat,lon) then 
				-- ok waypoint are can be shown on existing charts
				return 
			end
		end	
	end
	-- nothing found , generate new map
	map_pages[#map_pages + 1] = {scale     = default_scale,
								 chart     = default_chart,
								 rotation  = 0,--course,
								 latitude  = lat,
								 longitude = lon}
end

function generate_maps()
	if not map_pages then
		map_pages = {}
	end
	--add common set of charts
	map_pages[#map_pages + 1] = default_map(4)
	map_pages[#map_pages + 1] = default_map(5)
	map_pages[#map_pages + 1] = default_map(6)
end


number_of_additional_pages = 2
